package com.yicong.ants.ui.scenic;

import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.ToastUtils;
import com.cchao.simplelib.core.RxHelper;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.model.event.CommonEvent;
import com.cchao.simplelib.ui.adapter.StatefulBindMultiQuickAdapter;
import com.cchao.simplelib.ui.fragment.BaseStatefulFragment;
import com.google.gson.Gson;
import com.kennyc.view.MultiStateView;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yicong.ants.BR;
import com.yicong.ants.BuildConfig;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.bean.home.ScenicItemWrapper;
import com.yicong.ants.bean.scenic.ScenicItem;
import com.yicong.ants.databinding.ScenicListFragmentBinding;
import com.yicong.ants.manager.RouterHelper;
import com.yicong.ants.manager.http.RetrofitHelper;
import com.yicong.ants.utils.AmapHelper;
import com.yicong.ants.utils.L;
import com.yicong.ants.utils.PermissionsChecker;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * type 1：黄金版；2：豪华版 ；4：免预约, 5: 特惠景区
 * 豪华版、黄金版风景区
 *
 * @author cchao
 */
public class ScenicListFragment extends BaseStatefulFragment<ScenicListFragmentBinding> {
    StatefulBindMultiQuickAdapter<ScenicItemWrapper> mAdapter;
    String mScenicType;
    String mCityId = "0";
    /**
     * 搜索关键字
     */
    private String search_name;
    private View emptyView;

    @Override
    protected int getLayoutId() {
        return R.layout.scenic_list_fragment;
    }

    public ScenicListFragment setScenicType(String scenicType) {
        mScenicType = scenicType;
        return this;
    }

    @Override
    public void onEvent(CommonEvent event) {
        if (event.getCode() == Constants.Event.update_address) {
            loadPage(1);
        }
    }

    @Override
    protected void initEventAndData() {
        initAdapter();
        onLoadData();
    }

    private void initAdapter() {
//        mDataBind.recycler.setLayoutManager(new LinearLayoutManager(mContext));
        mAdapter = new StatefulBindMultiQuickAdapter<ScenicItemWrapper>(null) {

            @Override
            public Map<Integer, Integer> getTypeLayoutMap() {
                Map<Integer, Integer> map = new HashMap<>(8);
                map.put(0, R.layout.scenic_item);
                return map;
            }

            @Override
            protected void convert(DataBindViewHolder helper, ScenicItemWrapper data) {
                convertScenic(helper, (ScenicItem) data.getObject());
            }

            @Override
            public void loadPageData(int page) {
                loadPage(page);
            }

            private void convertScenic(DataBindViewHolder helper, ScenicItem item) {
                helper.getBinding().setVariable(BR.bean, item);
//                helper.setText(R.id.scenic_type, BusinessHelper.getScenicTypeExplain(mScenicType));
//                helper.setImageDrawable(R.id.level_label, UiHelper.getDrawable(BusinessHelper.ScenicLabelMap.get(mScenicType)));

                helper.setVisible(R.id.limit_text, false);
                switch (item.getScenic_type()) {
                    case "10":
                    case "20":
                        helper.setText(R.id.limit_text, "一年限一次");
                        helper.setVisible(R.id.limit_text, true);
                        break;
                    case "30":
                        helper.setText(R.id.limit_text, "不限次");
                        helper.setVisible(R.id.limit_text, true);
                        break;
                }
            }
        };
//        mAdapter.bindToRecyclerView(mDataBind.recycler);
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            ScenicItemWrapper scenicItemWrapper = mAdapter.getData().get(position);
            if (scenicItemWrapper.getItemType() > 0) {
                return;
            }
            RouterHelper.toScenicDetail(getActivity(), ((ScenicItem) scenicItemWrapper.getObject()).getScenic_id());
        });
    }

    @Override
    protected void onLoadData() {
        if (PermissionsChecker.checkPermissions(getContext(), Constants.LOCATION2)) {
            AmapHelper.startLocation(mContext, aMapLocation -> loadPage(1));
        } else if (Constants.Scenic_Type.SetAdvanceScenic.equals(mScenicType)) {
            UiHelper.showConfirmDialog(getContext(), "权限申请", "需要获取“获取位置”权限，开启后将可以用于展示用户周围的景点和获取位置相关的搜索和推荐功能",
                    (dialog, which) -> {
                        switch (which) {
                            case DialogInterface.BUTTON_POSITIVE:
                                addSubscribe(new RxPermissions(this)
                                        .request(Constants.LOCATION2)
                                        .subscribe(aBoolean -> {
                                            if (!aBoolean) {
                                                showToast("没有权限，无法定位所在地");
                                                loadPage(1);
                                                return;
                                            }
                                            AmapHelper.startLocation(mContext, aMapLocation -> loadPage(1));
                                        }));
                                AmapHelper.startLocation(mContext, aMapLocation -> loadPage(1));
                                break;
                            case DialogInterface.BUTTON_NEGATIVE:
                                ToastUtils.showLong("没有权限，无法定位所在地");
                                loadPage(1);
                                break;
                        }
                    });
        } else {
            loadPage(1);
        }
    }

    public void search(String mCityId, String search_name) {
        this.mCityId = mCityId;
        this.search_name = search_name;
        loadPage(1);
    }

    private void loadPage(final int page) {
        final Map<String, String> params = new HashMap<>();
        params.put("scenic_type", mScenicType);
        params.put("city_id", mCityId);
        if (null != search_name) {
            params.put("search_name", search_name);
        }
        params.put("page", String.valueOf(page));

        if (page == 1) {
            mAdapter.setViewState(MultiStateView.VIEW_STATE_LOADING);
        }
        addSubscribe(RetrofitHelper.getApis().getScenicList(params)
                .compose(RxHelper.toMain())
                .subscribe(respBean -> {
                    if (respBean.isCodeFail()) {
                        showToast(respBean.getMsg());
                        mAdapter.getData().clear();
                        mAdapter.loadMoreComplete();
                    }
//                onLoadAd(page);
                    // 包装数据
                    List<ScenicItem> data = respBean.getList();
                    List<ScenicItemWrapper> list = new ArrayList<>();
                    for (ScenicItem datum : data) {
                        list.add(ScenicItemWrapper.of(0, datum));
                    }
                    mAdapter.solvePageData(list, page, respBean.getPageInfo().getCountPage());
                    if (emptyView == null) {
                        emptyView = LayoutInflater.from(getContext()).inflate(R.layout.view_scenic_empty, null);
                        mAdapter.setEmptyView(emptyView);
                    }
                }, RxHelper.getSwitchableErrorConsumer(mAdapter)));
    }
}
